# !/usr/bin/env python
# -*-coding:utf-8 -*-
"""
# File       : flow_data_view.py
# Time       ：2023/9/17 11:30
# Author     ：Y-aong
# version    ：python 3.7
# Description：
    流程图数据
"""
import traceback

from flask import request
from flask_restx import fields

from apis.flow import flow_ns
from apis.orderlines.models import TaskInstance
from apis.orderlines.schema.task_schema import TaskInstanceSchema
from public.api_utils.api_decorator import handle_api_error
from public.base_model import db
from public.base_response import generate_response, MarshalModel
from public.base_view import AbstractView
from public.logger import logger
from public.utils.mongo_utils import MongoDBUtil

flow_data_get = {
    'process_id': fields.String(),
    'task_id': fields.String(),
}
flow_data_marshal = MarshalModel('flow_data', flow_ns)


class FlowDataView(AbstractView):
    url = '/data'

    def __init__(self, *args, **kwargs):
        super(FlowDataView, self).__init__(*args, **kwargs)
        self.flow_task_data = MongoDBUtil('flow_task_data')
        self.flow_data = MongoDBUtil('flow_data')
        self.filter_ = {'process_id': self.form_data.get('process_id')}
        if request.method == 'GET' or request.method == 'DELETE':
            self.form_data: dict = request.args
        else:
            self.form_data: dict = request.json
        self.process_instance_id = self.form_data.get('process_instance_id')
        self.is_logger = True

    def get_flow_data(self):

        flow_data = self.flow_data.collection.find_one(self.filter_)
        if flow_data and '_id' in flow_data:
            flow_data.pop('_id')
        return flow_data

    def get_task_instance(self):
        objs = db.session.query(TaskInstance).filter(
            TaskInstance.active == 1,
            TaskInstance.process_instance_id == self.process_instance_id
        ).all()

        return TaskInstanceSchema().dump(objs, many=True)

    @handle_api_error()
    @flow_ns.doc(description='获取流程图数据')
    def get(self):
        """获取流程图数据"""
        try:
            flow_data = self.get_flow_data()
            if flow_data is None:
                return generate_response({}, message=f'当前没有流程数据,{self.filter_}')
            nodes = flow_data.get('graphData').get('nodes')
            if self.process_instance_id:
                logger.info('当前为流程运行中')
                task_instance_info = self.get_task_instance()
                for node in nodes:
                    for task_instance in task_instance_info:
                        if node.get('id') == task_instance.get('task_id'):
                            properties = node.get('properties')
                            properties['status'] = task_instance.get('task_status')
            return generate_response(flow_data)
        except Exception as e:
            logger.info(f'当前没有流程数据::{e}\n{traceback.format_exc()}')
            return generate_response({}, message='当前没有流程数据')

    @handle_api_error()
    @flow_ns.doc(description='创建流程节点')
    def post(self):
        """创建流程节点"""
        filter_ = {'process_id': self.form_data.get('process_id'), 'task_id': self.form_data.get('task_id')}
        self.flow_task_data.collection.update_one(filter=filter_, update={'$set': self.form_data}, upsert=True)
        self.flow_data.collection.update_one(filter=filter_, update={'$set': self.form_data}, upsert=True)
        return generate_response(message='流程图数据设置成功')
